#!/usr/bin/python 
# @Time  : 2022/4/27 14:46
# @Author: LOUIE
# @Desc  : 钉钉消息
from dingtalkchatbot.chatbot import DingtalkChatbot
from utils.logger import log


class DingTalk:

    def __init__(self, hook: str, title: str = 'YanXuan'):
        self.robot = DingtalkChatbot(hook)
        self.title = title

    def build_content_to_ding(self, result: dict):
        """
        :return:
        """
        content = f"## **YanXuan Mall Summary**\n" \
                  f"##### Time ：{result['start_time']}\n" \
                  f"##### Duration ：{result['duration']}\n" \
                  f"##### Total API ：{result['total']}\n" \
                  f"##### Passed ：{result['passed']}\n" \
                  f"##### Failed ：{result['failed']}\n"\
                  f"##### Success percent ：{result['passed_percent']}\n"
        return content

    def send_message_to_ding(self, result: dict, **kwargs):
        try:
            content = self.build_content_to_ding(result)
            self.robot.send_markdown(title=self.title, text=content, **kwargs)
            log.info("Ding message sending succeeded.")
        except Exception as e:
            log.info("Failed to send ding message！Error: {}".format(e))


if __name__ == '__main__':
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=fdca1518999b1768b24a8364107129233221a5861e3c384e22d3c3ad7d42a1f8'
    ding = DingTalk(webhook)
    from utils.tools import result, parse_summary
    result = parse_summary(result)
    print(result)
    ding.send_message_to_ding(result, at_mobiles=[15338807445])
